package com.yuanqiworld.vw.filter;

import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

/**
 * 请求头过滤器.
 */
public class HiddenAcceptHeaderFilter extends OncePerRequestFilter {

    /**
     * Default method parameter: <code>_accept</code>
     */
    public static final String DEFAULT_ACCEPT_PARAM = "_accept";

    private String acceptParam = DEFAULT_ACCEPT_PARAM;

    /**
     * Set the parameter name to look for HTTP methods.
     *
     * @see #DEFAULT_ACCEPT_PARAM
     */
    public void setAcceptParam(String acceptParam) {
        Assert.hasText(acceptParam, "'acceptParam' must not be empty");
        this.acceptParam = acceptParam;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String paramValue = request.getParameter(this.acceptParam);
        if ("JSON".equalsIgnoreCase(paramValue)) {
            HttpServletRequest wrapper = new HttpExtendHeaderRequestWrapper(request, "Accept", "application/json");
            filterChain.doFilter(wrapper, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * Simple {@link HttpServletRequest} wrapper that returns the supplied method for {@link HttpServletRequest#getMethod()}.
     */
    private static class HttpExtendHeaderRequestWrapper extends HttpServletRequestWrapper {

        private final String headerName;
        private final String headerValue;
        private final Vector headers;

        public HttpExtendHeaderRequestWrapper(HttpServletRequest request, String headerName, String headerValue) {
            super(request);
            this.headerName = headerName;
            this.headerValue = headerValue;

            headers = new Vector();
            Enumeration headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                headers.add(headerNames.nextElement());
            }
            headers.add(headerName + "=" + headerValue);
        }

        @Override
        public String getHeader(String name) {
            if (name.equals(headerName)) {
                return headerValue;
            }
            return super.getHeader(name);
        }

        @Override
        public Enumeration getHeaderNames() {
            return headers.elements();
        }
    }
}
